import {Injectable} from '@angular/core';
import {ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot, UrlTree} from '@angular/router';
import {Observable, of} from 'rxjs';
import {Authenticate} from './authenticate.service';
import {mergeMap} from 'rxjs/operators';


@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements CanActivate {

  constructor(private authService: Authenticate,
              private router: Router) {
  }

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean | UrlTree> | boolean {
    const url: string = state.url;
    const code = route.queryParamMap.get('code');
    const openid = route.queryParamMap.get('openid');
    return this.checkLogin(url, code, openid);
  }


  checkLogin(url: string, code?: string, openid?: string): Observable<boolean | UrlTree> | boolean {

    if (this.authService.isLoggedIn) {
      return true;
    }
    // Store the attempted URL for redirecting
    this.authService.redirectUrl = url;

    if (code) {
      return this.authService.first(code).pipe(mergeMap(r => this.routerCtr(r)));
    }

    if (openid) {
      return this.authService.byOpenid(openid).pipe(mergeMap(r => this.routerCtr(r)));
    }

    return this.authService.authentication().pipe(mergeMap(r => this.routerCtr(r)));
  }


  private routerCtr(r: boolean): Observable<boolean> {
    if (r) {
      this.router.navigateByUrl(this.authService.redirectUrl);
    } else {
      this.router.navigateByUrl('/none-auth');
    }
    return of(r);
  }
}
